package security.dao;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import security.model.Corporation;

@Stateless
public class CorporationDAO {

    @PersistenceContext(unitName = "persistence")
    private EntityManager em;

    public Corporation getById(Integer id) {
        return em.find(Corporation.class, id);
    }

    public Corporation save(Corporation organization) {
        em.persist(organization);
        return organization;
    }

    public Corporation update(Corporation organization) {
        return em.merge(organization);
    }

    public void delete(Integer id) {
        em.remove(em.find(Corporation.class, id));
    }

    @SuppressWarnings("unchecked")
    public List<Corporation> list(int first, int max) {
        Query query = em.createQuery("SELECT e FROM Corporation e ORDER BY e.name ASC");
        if (max > 0) {
            query.setMaxResults(max);
        }
        if (first > 0) {
            query.setFirstResult(first);
        }
        return query.getResultList();
    }

    //-------------------------------------------------------------------
    public Corporation getByCode(Long code) {
        Corporation result = null;
        Query query = em.createQuery("SELECT e FROM Corporation e WHERE e.code=:code");
        query.setParameter("code", code);
        try {
            result = (Corporation) query.getSingleResult();
        } catch (NoResultException e) {
            //e.printStackTrace();
        }
        return result;
    }

    public Long getTotal() {
        Query query = em.createQuery("SELECT COUNT(e) FROM Corporation e");
        return (Long) query.getSingleResult();
    }

}
